﻿using System;
using System.ComponentModel;
using System.Deployment.Application;
using System.Drawing;
using System.Windows.Forms;

namespace WMR_Data_Logger
{
    public class Update : Form
    {
        private Button button1;
        private Button button2;
        private IContainer components;
        private Label downloadStatus;
        private Label downloadStatus2;
        private GroupBox groupBox1;
        private Label label1;
        private Label label2;
        private Label label3;
        private Label label4;
        private Label lb_heading;
        private Label lbl_done;
        private Label lbl_from;
        private Label lbl_name;
        private string newVersion = "";
        private PictureBox pb_WMR200;
        private PictureBox pictureBox1;
        private long sizeOfUpdate;
        private ProgressBar ud_progress;

        public Update()
        {
            InitializeComponent();
        }

        private void ad_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("ERROR: Could not retrieve new version of the application. Reason: \n" + e.Error.Message +
                                "\nPlease report this error to the system administrator.");
            }
            else
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("The update was cancelled.");
                }
                if (e.UpdateAvailable)
                {
                    sizeOfUpdate = e.UpdateSizeBytes;
                    newVersion = e.AvailableVersion.ToString();
                }
            }
        }

        private void ad_CheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            downloadStatus.Text = string.Format("Downloading: {0}.", GetProgressString(e.State));
            downloadStatus2.Text = string.Format("{1:D}K of {2:D}K downloaded.", e.BytesCompleted/0x400L,
                                                 e.BytesTotal/0x400L);
            if (e.BytesTotal > 0L)
            {
                lbl_done.Text = (((e.BytesCompleted/e.BytesTotal)*100L)).ToString() + "%";
            }
        }

        private void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("The update of the application's latest version was cancelled.");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: \n" +
                                e.Error.Message + "\nPlease report this error to the system administrator.");
            }
            else
            {
                var result =
                    MessageBox.Show(
                        "The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)",
                        "Restart Application", MessageBoxButtons.OKCancel);
                if (DialogResult.OK == result)
                {
                    Application.Restart();
                }
            }
        }

        private void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            var str = string.Format("{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted/0x400L,
                                    e.BytesTotal/0x400L, e.ProgressPercentage);
            downloadStatus.Text = str;
            ud_progress.Value = e.ProgressPercentage;
            lbl_done.Text = e.ProgressPercentage.ToString() + "%";
        }

        private void BeginUpdate()
        {
            var currentDeployment = ApplicationDeployment.CurrentDeployment;
            currentDeployment.UpdateCompleted += ad_UpdateCompleted;
            var isFirstRun = currentDeployment.IsFirstRun;
            var updatedApplicationFullName = currentDeployment.UpdatedApplicationFullName;
            currentDeployment.UpdateLocation.ToString();
            currentDeployment.UpdateAsyncCancel();
            currentDeployment.UpdateProgressChanged += ad_UpdateProgressChanged;
            currentDeployment.UpdateAsync();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            UpdateApplication();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private string GetProgressString(DeploymentProgressState state)
        {
            if (state == DeploymentProgressState.DownloadingApplicationFiles)
            {
                return "application files";
            }
            if (state == DeploymentProgressState.DownloadingApplicationInformation)
            {
                return "application manifest";
            }
            return "deployment manifest";
        }

        private void InitializeComponent()
        {
            var manager = new ComponentResourceManager(typeof (Update));
            downloadStatus = new Label();
            lb_heading = new Label();
            groupBox1 = new GroupBox();
            label1 = new Label();
            lbl_done = new Label();
            pictureBox1 = new PictureBox();
            label2 = new Label();
            ud_progress = new ProgressBar();
            label3 = new Label();
            label4 = new Label();
            lbl_name = new Label();
            lbl_from = new Label();
            pb_WMR200 = new PictureBox();
            button1 = new Button();
            button2 = new Button();
            downloadStatus2 = new Label();
            groupBox1.SuspendLayout();
            ((ISupportInitialize) pictureBox1).BeginInit();
            ((ISupportInitialize) pb_WMR200).BeginInit();
            base.SuspendLayout();
            downloadStatus.AutoSize = true;
            downloadStatus.Location = new Point(0x9b, 0x72);
            downloadStatus.Name = "downloadStatus";
            downloadStatus.Size = new Size(0xb6, 13);
            downloadStatus.TabIndex = 0;
            downloadStatus.Text = "Press continue to update application.";
            lb_heading.AutoSize = true;
            lb_heading.Font = new Font("Arial Narrow", 15.75f, FontStyle.Bold, GraphicsUnit.Point, 0);
            lb_heading.ForeColor = Color.DimGray;
            lb_heading.Location = new Point(30, 0xa6);
            lb_heading.Name = "lb_heading";
            lb_heading.Size = new Size(0x55, 0x19);
            lb_heading.TabIndex = 1;
            lb_heading.Text = "WMR200";
            groupBox1.BackColor = Color.White;
            groupBox1.Controls.Add(label1);
            groupBox1.Controls.Add(lbl_done);
            groupBox1.Controls.Add(pictureBox1);
            groupBox1.Controls.Add(label2);
            groupBox1.Dock = DockStyle.Top;
            groupBox1.Location = new Point(0, 0);
            groupBox1.Name = "groupBox1";
            groupBox1.Size = new Size(0x18b, 0x3e);
            groupBox1.TabIndex = 3;
            groupBox1.TabStop = false;
            label1.AutoSize = true;
            label1.Font = new Font("Microsoft Sans Serif", 9.75f, FontStyle.Bold, GraphicsUnit.Point, 0);
            label1.ForeColor = Color.DimGray;
            label1.Location = new Point(10, 9);
            label1.Name = "label1";
            label1.Size = new Size(0x11b, 0x10);
            label1.TabIndex = 3;
            label1.Text = "Updateing WMR200 Data Logger Sniffer";
            lbl_done.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            lbl_done.AutoSize = true;
            lbl_done.BackColor = Color.Transparent;
            lbl_done.FlatStyle = FlatStyle.System;
            lbl_done.Font = new Font("Arial Narrow", 9.75f, FontStyle.Bold, GraphicsUnit.Point, 0);
            lbl_done.ForeColor = Color.Black;
            lbl_done.Location = new Point(0x16a, 0x2b);
            lbl_done.Margin = new Padding(0);
            lbl_done.Name = "lbl_done";
            lbl_done.Size = new Size(0x17, 0x10);
            lbl_done.TabIndex = 6;
            lbl_done.Text = "0%";
            pictureBox1.BackColor = Color.Transparent;
            pictureBox1.Location = new Point(0x138, 8);
            pictureBox1.Name = "pictureBox1";
            pictureBox1.Size = new Size(80, 50);
            pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
            pictureBox1.TabIndex = 5;
            pictureBox1.TabStop = false;
            label2.AutoSize = true;
            label2.ForeColor = Color.Gray;
            label2.Location = new Point(0x19, 0x1a);
            label2.Name = "label2";
            label2.Size = new Size(0x120, 0x1a);
            label2.TabIndex = 4;
            label2.Text =
                "This may take several minutes. You can use your computer \r\n to do other tasks during the installation.";
            ud_progress.Location = new Point(0x9d, 0x91);
            ud_progress.Name = "ud_progress";
            ud_progress.Size = new Size(0xdf, 0x12);
            ud_progress.TabIndex = 4;
            label3.AutoSize = true;
            label3.Location = new Point(0x9b, 0x45);
            label3.Name = "label3";
            label3.Size = new Size(0x26, 13);
            label3.TabIndex = 5;
            label3.Text = "Name:";
            label4.AutoSize = true;
            label4.Location = new Point(0x9b, 0x5b);
            label4.Name = "label4";
            label4.Size = new Size(0x21, 13);
            label4.TabIndex = 6;
            label4.Text = "From:";
            lbl_name.AutoSize = true;
            lbl_name.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0);
            lbl_name.Location = new Point(190, 0x45);
            lbl_name.Name = "lbl_name";
            lbl_name.Size = new Size(0xae, 13);
            lbl_name.TabIndex = 8;
            lbl_name.Text = "WMR200 Data Logger Sniffer";
            lbl_from.AutoSize = true;
            lbl_from.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0);
            lbl_from.Location = new Point(190, 0x5b);
            lbl_from.Name = "lbl_from";
            lbl_from.Size = new Size(0x73, 13);
            lbl_from.TabIndex = 9;
            lbl_from.Text = "www.bashewa.com";
            pb_WMR200.BackgroundImageLayout = ImageLayout.None;
            pb_WMR200.Location = new Point(9, 0x44);
            pb_WMR200.Name = "pb_WMR200";
            pb_WMR200.Size = new Size(130, 0x5f);
            pb_WMR200.TabIndex = 10;
            pb_WMR200.TabStop = false;
            button1.DialogResult = DialogResult.Cancel;
            button1.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0);
            button1.ForeColor = Color.Red;
            button1.Location = new Point(0x9d, 0xa8);
            button1.Name = "button1";
            button1.Size = new Size(0x56, 0x17);
            button1.TabIndex = 11;
            button1.Text = "CANCEL";
            button1.UseVisualStyleBackColor = true;
            button1.Click += button1_Click;
            button2.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0);
            button2.ForeColor = Color.Green;
            button2.Location = new Point(0x127, 0xa8);
            button2.Name = "button2";
            button2.Size = new Size(0x55, 0x17);
            button2.TabIndex = 12;
            button2.Text = "CONTINUE";
            button2.UseVisualStyleBackColor = true;
            button2.Click += button2_Click;
            downloadStatus2.AutoSize = true;
            downloadStatus2.Location = new Point(0x9b, 0x81);
            downloadStatus2.Name = "downloadStatus2";
            downloadStatus2.Size = new Size(0, 13);
            downloadStatus2.TabIndex = 13;
            base.AutoScaleDimensions = new SizeF(6f, 13f);
            base.AutoScaleMode = AutoScaleMode.Font;
            base.CancelButton = button1;
            base.ClientSize = new Size(0x18b, 0xc4);
            base.Controls.Add(downloadStatus2);
            base.Controls.Add(button2);
            base.Controls.Add(button1);
            base.Controls.Add(pb_WMR200);
            base.Controls.Add(lbl_from);
            base.Controls.Add(lbl_name);
            base.Controls.Add(label4);
            base.Controls.Add(label3);
            base.Controls.Add(ud_progress);
            base.Controls.Add(groupBox1);
            base.Controls.Add(lb_heading);
            base.Controls.Add(downloadStatus);
            base.MaximizeBox = false;
            base.MinimizeBox = false;
            base.Name = "Update";
            base.StartPosition = FormStartPosition.CenterScreen;
            Text = "Updateing WMR200 Data Logger Sniffer";
            base.TopMost = true;
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
            ((ISupportInitialize) pictureBox1).EndInit();
            ((ISupportInitialize) pb_WMR200).EndInit();
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        public void InstallUpdateSyncWithInfo()
        {
            UpdateCheckInfo info = null;
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                var currentDeployment = ApplicationDeployment.CurrentDeployment;
                try
                {
                    info = currentDeployment.CheckForDetailedUpdate();
                }
                catch (DeploymentDownloadException exception)
                {
                    MessageBox.Show(
                        "The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " +
                        exception.Message);
                    return;
                }
                catch (InvalidDeploymentException exception2)
                {
                    MessageBox.Show(
                        "Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " +
                        exception2.Message);
                    return;
                }
                catch (InvalidOperationException exception3)
                {
                    MessageBox.Show(
                        "This application cannot be updated. It is likely not a ClickOnce application. Error: " +
                        exception3.Message);
                    return;
                }
                if (info.UpdateAvailable)
                {
                    var flag = true;
                    if (!info.IsUpdateRequired)
                    {
                        var result =
                            MessageBox.Show("An update is available. Would you like to update the application now?",
                                            "Update Available", MessageBoxButtons.OKCancel);
                        if (DialogResult.OK != result)
                        {
                            flag = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show(
                            "This application has detected a mandatory update from your current version to version " +
                            info.MinimumRequiredVersion + ". The application will now install the update and restart.",
                            "Update Available", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    if (flag)
                    {
                        try
                        {
                            currentDeployment.Update();
                            MessageBox.Show("The application has been upgraded, and will now restart.");
                            Application.Restart();
                        }
                        catch (DeploymentDownloadException exception4)
                        {
                            MessageBox.Show(
                                "Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " +
                                exception4);
                        }
                    }
                }
            }
        }

        private void UpdateApplication()
        {
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                var currentDeployment = ApplicationDeployment.CurrentDeployment;
                currentDeployment.CheckForUpdateCompleted += ad_CheckForUpdateCompleted;
                currentDeployment.CheckForUpdateProgressChanged += ad_CheckForUpdateProgressChanged;
                currentDeployment.CheckForUpdateAsync();
            }
            else
            {
                MessageBox.Show("This application can not be updated.\nIt has not been installed with ClickOnce.",
                                "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
            }
        }
    }
}